package util;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class MyFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    //请求和相应时都会执行doFilter()方法
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //处理请求乱码
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        request.setCharacterEncoding("utf-8");

        //防止用户在未登录的情况下访问资源
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求地址
        String requestURI = request.getRequestURI();

        //获取用户session信息
        Object users = request.getSession().getAttribute("u1");

        //endsWith()方法,判断字符串是否已xxx结束；字符串以xxx开始可用startsWith()方法
        //过滤页面，如果没有用户登录信息则跳转到登录页面，而不能直接进入主页
        if (requestURI.endsWith("index.jsp")&&users==null){
            //处理响应乱码
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("<script>top.location.href='login.jsp';</script>");
        }

        // Filter 只是链式处理，请求依然转发到目的地址
        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {


    }
}
